<?php
class o2o_ctl_admin_store extends desktop_controller {

    var $name = "门店管理";
    var $workground = "goods_manager";

    function index() {
        $obj_organizations_op = kernel::single('organization_operation');
        $this->pagedata['organization'] = $obj_organizations_op->getGropById();
        $this->page('admin/organization/treeList.html');
    }

    //展示页面获取下架组织信息
    public function getChildNode(){
        $obj_organizations_op = kernel::single('organization_operation');
        $this->pagedata['organization'] = $obj_organizations_op->getGropById($_POST['orgId']);
        $this->display('admin/organization/sub_treeList.html');
    }

    /*
     * 添加门店
     */
    function add($org_id=NULL,$p_org_id=NULL) {
        $this->_edit($org_id,$p_org_id);
    }

    /*
     * 编辑门店
     */
    function edit($org_id=NULL,$p_org_id=NULL) {
        $this->_edit($org_id,$p_org_id);
    }

    function _edit($org_id=NULL,$p_org_id=NULL) {
        $orgObj = app::get('organization')->model('organization');
        $storeObj = $this->app->model('store');

        if ($org_id) {
            $org_id = intval($org_id);
            $org_info = $orgObj->dump($org_id);
            $this->pagedata['org_info'] = $org_info;

            $storeObj = $this->app->model('store');
            $store_prop = $storeObj->dump(array("store_bn"=>$org_info['org_no']),"*");
            $this->pagedata["store_prop"] = $store_prop;
        }
        
        if($p_org_id){
            //当前所属的组织架构
            $p_org_id = intval($p_org_id);
            $p_org_info = $orgObj->dump(array("org_id"=>$p_org_id),"*");
            $this->pagedata["p_org_info"] = $p_org_info;
        }

        $serverObj = $this->app->model("server");
        $serverList = $serverObj->getList('server_id,name',array());
        $this->pagedata['serverList'] = $serverList;

        $this->path[] = array('text'=>'添加/编辑门店');
        $this->display("admin/system/store.html");
    }

    function save() {
        $organizationObj = app::get('organization')->model('organization');
        $storeObj = $this->app->model('store');

        $url = 'index.php?app=o2o&ctl=admin_store&act=index';
        $this->begin($url);
        $org_data = $_POST['org'];
        $store_prop_data = $_POST['store_prop'];

        //表单验证
        if (strlen($store_prop_data['zip']) <> '6') {
            $this->end(false, '请输入正确的邮编');
        }
        //固定电话与手机必填一项
        $gd_tel = str_replace(" ", "", $store_prop_data['tel']);
        $mobile = str_replace(" ", "", $store_prop_data['mobile']);
        if (!$gd_tel && !$mobile) {
            $this->end(false, '固定电话与手机号码必需填写一项');
        }
        $pattern = "/^400\d{7}$/";
        $pattern1 = "/^\d{1,4}-\d{7,8}(-\d{1,6})?$/i";
        if ($gd_tel) {
            $_rs = preg_match($pattern, $gd_tel);
            $_rs1 = preg_match($pattern1, $gd_tel);
            if ((!$_rs) && (!$_rs1)) {
                $this->end(false, '请填写正确的固定电话号码');
            }
        }

        $pattern2 = "/^\d{8,15}$/i";
        if ($mobile) {
            if (!preg_match($pattern2, $mobile)) {
                $this->end(false, '请输入正确的手机号码');
            }
            if ($mobile[0] == '0') {
                $this->end(false, '手机号码前请不要加0');
            }
        }

        //识别是新增还是编辑
        $is_new_add = intval($org_data['org_id']) ? false : true;

        if($is_new_add){
            $check_org_no_exist = $organizationObj->dump(array("org_no"=>$org_data["org_no"]),"org_id");
            if($check_org_no_exist){
                $this->end(false,'编码已经存在');
            }

            $check_org_name_exist = $organizationObj->dump(array("org_name"=>$org_data["org_name"]),"org_id");
            if($check_org_name_exist){
                $this->end(false,'名称已经存在');
            }
            
        }else{
            $check_org_no_exist = $organizationObj->dump(array("org_no"=>$org_data["org_no"]),"org_id");
            if($check_org_no_exist && $check_org_no_exist['org_id'] != $org_data['org_id']){
                $this->end(false,'编码已经存在');
            }

            $check_org_name_exist = $organizationObj->dump(array("org_name"=>$org_data["org_name"]),"org_id");
            if($check_org_name_exist && $check_org_name_exist['org_id'] != $org_data['org_id']){
                $this->end(false,'名称已经存在');
            }

            //编辑的时候，取一下门店原有的信息
            $old_org_info = $organizationObj->dump(array("org_id"=>$org_data['org_id']),"org_id,parent_id");
        }

        $org_save_data = array(
            'org_name'=> $org_data["org_name"],
            'org_type' => 2,
            'org_no' => $org_data["org_no"],
            'status' => $org_data['status'],
            'area' => $org_data['area'],
        );

        if(!$is_new_add){
            $org_save_data['org_id'] = $org_data['org_id'];
        }

        $org_save_data['parent_id'] = $org_data['org_p_id'] ? intval($org_data['org_p_id']) : '';
        if($org_save_data['parent_id']){
            $p_org_info = $organizationObj->dump(array("org_id"=>$org_save_data['parent_id']),"org_id,org_name,org_level_num,org_parents_structure,haschild");
            if(!$p_org_info["org_parents_structure"] && $p_org_info["org_level_num"] == 1){
                //此为最上层级 org_level_num是1
                $org_save_data["org_parents_structure"] = 'mainOrganization:'.$p_org_info['org_name'].':'.$p_org_info['org_id'];
                $org_save_data['org_level_num'] = 2;
            }else{
                list($package,$t_org_name,$t_org_id) = explode(':',$p_org_info["org_parents_structure"]);
                $org_save_data["org_parents_structure"] = $package.':'.$t_org_name."/".$p_org_info['org_name'].':'.$p_org_info['org_id'];
                $org_save_data['org_level_num'] = $p_org_info["org_level_num"]+1;
            }
        }else{
            $org_save_data["org_parents_structure"] = $org_data['org_parents_structure'];
            if($org_save_data["org_parents_structure"]){
                $tmp_org_path_arr = explode(':',$org_save_data["org_parents_structure"]);
                $org_save_data['parent_id'] = $tmp_org_path_arr[2];
                $p_org_info = $organizationObj->dump(array("org_id"=>$org_save_data['parent_id']),"org_level_num,haschild");
                $org_save_data['org_level_num'] = $p_org_info["org_level_num"]+1;
            }else{
                $org_save_data['parent_id'] = 0;
                $org_save_data['org_level_num'] = 1;
            }
        }

        #格式化关联地区信息 ExBOY
        $storeRegionObj    = $this->app->model('store_regions');
        $o2o_region        = kernel::single('o2o_store_regions');
        
        list($temp_package, $temp_region_name, $region_id)    = explode(':', $org_save_data['area']);
        $region_data   = $o2o_region->getRegionById($region_id);
        
        $is_done = true;
        //开启事务
        $organizationObj->db->exec('begin');

        $is_save = $organizationObj->save($org_save_data);
        if($is_save){
            //发送短信签名注册
            if (defined('APP_TOKEN') && defined('APP_SOURCE')) {
                base_kvstore::instance('taoexlib')->fetch('account', $account);
                if (unserialize($account)) {
                    $sms_sign = '【'.$org_save_data['org_name'].'】';
                    kernel::single('taoexlib_request_sms')->newoauth_request(array('sms_sign'=>$sms_sign));
                }
            }

            //如果设定了门店服务端类型获取对应的虚拟仓储类型
            if($store_prop_data['server_id']){
                $serverObj = $this->app->model('server');
                $serverInfo = $serverObj->dump(array('server_id'=>$store_prop_data['server_id']),'type');
                if($serverInfo['type']){
                    $wms_type = kernel::single('channel_interface_channel')->dump(array('channel_type'=>'wms','node_type'=>$serverInfo['type']),'channel_id');
                    $now_wms_id = $wms_type['channel_id'];
                }
            }

            if($is_new_add){
                //保存门店的扩展属性信息
                $sdf = array(
                    'store_bn' => $org_save_data['org_no'],
                    'name' => $org_save_data['org_name'],
                    'server_id' => $store_prop_data['server_id'],
                    'addr' => $store_prop_data['addr'],
                    'area' => $org_save_data['area'],
                    'zip' => $store_prop_data['zip'],
                    'contacter' => $store_prop_data['contacter'],
                    'mobile' => $store_prop_data['mobile'],
                    'tel' => $store_prop_data['tel'],
                    'store_type' => $store_prop_data['store_type'],
                    'self_pick' => $store_prop_data['self_pick'],
                    'distribution' => $store_prop_data['distribution'],
                    'aftersales' => $store_prop_data['aftersales'],
                    'confirm' => $store_prop_data['confirm'],
                    'status' => $org_save_data['status'],
                );
                $store_save = $storeObj->save($sdf);
                if(!$store_save){
                    $organizationObj->db->rollBack();
                    $error_msg = '门店扩展信息新增失败';
                    $is_done = false;
                }

                //如果门店信息新建保存成功，直接生成对应的虚拟仓和店铺
                $custom_bn = $org_save_data['org_no'];
                $custom_name = $org_save_data['org_name'];

                $new_branch = array(
                    'branch_bn' => $custom_bn,
                    'name' => $custom_name,
                    'storage_code' => $custom_bn,
                    'b_type' => 2,
                    'b_status' => $org_save_data['status'],
                    'wms_id' => $now_wms_id,
                );

                $save_branch = kernel::single('ome_interface_branch')->save($new_branch);
                if(!$save_branch){
                    $organizationObj->db->rollBack();
                    $error_msg = '门店关联虚拟仓保存失败，编码可能被占用';
                    $is_done = false;
                }

                $new_shop = array(
                    'shop_bn' => $custom_bn,
                    'name' => $custom_name,
                    's_type' => 2,
                    's_status' => $org_save_data['status'],
                );
                $save_shop = kernel::single('ome_interface_shop')->save($new_shop);
                if(!$save_shop){
                    $organizationObj->db->rollBack();
                    $error_msg = '门店关联线下店铺保存失败，编码可能被占用';
                    $is_done = false;
                }

                //更新相关的仓库和店铺
                $update_store = $storeObj->update(array('branch_id'=>$new_branch['branch_id'],'shop_id'=>$new_shop['shop_id']),array('store_id'=>$sdf['store_id']));
                if(!$update_store){
                    $organizationObj->db->rollBack();
                    $error_msg = '门店关联仓库、店铺信息更新失败';
                    $is_done = false;
                }
                
                #新增门店关联地区数据信息 ExBOY
                $save_data = array(
                    'store_id' => $sdf['store_id'],
                    'region_1' => intval($region_data[1]),
                    'region_2' => intval($region_data[2]),
                    'region_3' => intval($region_data[3]),
                    'region_4' => intval($region_data[4]),
                    'region_5' => intval($region_data[5]),
                );
                $save_region    = $storeRegionObj->save($save_data);
                if(!$save_region)
                {
                    $organizationObj->db->rollBack();
                    $error_msg = '门店关联地区信息保存失败';
                    $is_done = false;
                }
            }else{
                //保存门店的扩展属性信息
                $update_data = array(
                    'store_bn' => $org_save_data['org_no'],
                    'name' => $org_save_data['org_name'],
                    'server_id' => $store_prop_data['server_id'],
                    'addr' => $store_prop_data['addr'],
                    'area' => $org_save_data['area'],
                    'zip' => $store_prop_data['zip'],
                    'contacter' => $store_prop_data['contacter'],
                    'mobile' => $store_prop_data['mobile'],
                    'tel' => $store_prop_data['tel'],
                    'store_type' => $store_prop_data['store_type'],
                    'self_pick' => $store_prop_data['self_pick'],
                    'distribution' => $store_prop_data['distribution'],
                    'aftersales' => $store_prop_data['aftersales'],
                    'confirm' => $store_prop_data['confirm'],
                    'status' => $org_save_data['status'],
                );
                $store_save = $storeObj->update($update_data,array('store_bn'=>$org_save_data['org_no']));
                if(!$store_save){
                    $organizationObj->db->rollBack();
                    $error_msg = '门店扩展信息更新失败';
                    $is_done = false;
                }

                //组织结构变更，更新店铺、仓库的状态字段
                $store_prop_info = $storeObj->getList('store_id, branch_id,shop_id',array('store_bn'=>$org_save_data['org_no']), 0, 1);
                //更新仓储信息
                $save_branch = kernel::single('ome_interface_branch')->update(array('b_status'=>$org_save_data['status'],'wms_id' => $now_wms_id,'name'=>$org_save_data['org_name']),array('branch_id'=>$store_prop_info[0]['branch_id']));
                //更新店铺信息
                $save_shop = kernel::single('ome_interface_shop')->update(array('s_status'=>$org_save_data['status'],'name'=>$org_save_data['org_name']),array('shop_id'=>$store_prop_info[0]['shop_id']));

                #更新门店关联地区数据信息 ExBOY
                $update_data = array(
                    'region_1' => intval($region_data[1]),
                    'region_2' => intval($region_data[2]),
                    'region_3' => intval($region_data[3]),
                    'region_4' => intval($region_data[4]),
                    'region_5' => intval($region_data[5]),
                );
                $save_region    = $storeRegionObj->update($update_data, array('store_id'=>$store_prop_info[0]['store_id']));
                if(!$save_region)
                {
                    $organizationObj->db->rollBack();
                    $error_msg = '门店关联地区信息更新失败';
                    $is_done = false;
                }
            }

            //如果最新保存的信息有父节点，更新父节点为有下级仓库或门店节点信息
            if($org_save_data['parent_id'] > 0){
                $child_arr = $organizationObj->getList("org_id",array("parent_id"=>$org_save_data['parent_id'],'org_type'=>2), 0, -1);
                if(count($child_arr) > 0){
                    $org_save_parent_data['haschild'] = $p_org_info['haschild'] | 2;
                }else{
                    $org_save_parent_data['haschild'] = $p_org_info['haschild'] ^ 2;
                }
                $organizationObj->update($org_save_parent_data,array('org_id'=>$org_save_data['parent_id']));
            }

            //处理原来选中的父节点
            if($old_org_info['parent_id'] > 0){
                $p_org_info = $organizationObj->dump(array("org_id"=>$old_org_info['parent_id']),"haschild");
                $child_arr = $organizationObj->getList("org_id",array("parent_id"=>$old_org_info['parent_id'],'org_type'=>2), 0, -1);
                if(count($child_arr) > 0){
                    $org_save_parent_data['haschild'] = $p_org_info['haschild'] | 2;
                }else{
                    $org_save_parent_data['haschild'] = $p_org_info['haschild'] ^ 2;
                }
                $organizationObj->update($org_save_parent_data,array('org_id'=>$old_org_info['parent_id']));
            }
        }

        $organizationObj->db->commit();

        $error_msg = $error_msg ? $error_msg : '保存失败';
        $msg = $is_done ? '保存成功' : $error_msg;

        $this->end($is_done, $msg);
    }

    public function toRemoveStore($org_id){
        $this->begin('index.php?app=o2o&ctl=admin_store&act=index');
        
        $org_id = intval($org_id);
        if(!$org_id){
            $this->end(false,'参数错误！');
        }

        $orgObj = app::get('organization')->model('organization');
        $storeObj = app::get('o2o')->model('store');
        $orderObj = app::get('ome')->model('orders');
        $deliveryObj = app::get('ome')->model('delivery');
        $arr_store = array();
        $tmp_shop_store = array();
        $tmp_branch_store = array();
        $tmp_shops = array();
        $tmp_branches = array();

        $org_arr = $orgObj->getList('org_id,org_no,parent_id',array('org_id' => $org_id));
        $org_info = $org_arr[0];

        $store_info = $storeObj->getList('store_id,store_bn,name,shop_id,branch_id',array('store_bn' => $org_info['org_no']), 0, 1);
        $store_id = $store_info[0]['store_id'];
        $store_bn = $store_info[0]['store_bn'];
        $store_name = $store_info[0]['name'];
        $shop_id = $store_info[0]['shop_id'];
        $branch_id = $store_info[0]['branch_id'];

        //检查门店关联的店铺是否有订单
        if($shop_id){
            $row = $orderObj->getList('shop_id',array('shop_id' => $shop_id));
            if($row){
                $error_msg = $store_name.'已有订单数据，不能删除';
                $this->end(false,$error_msg);
            }
        }

        //检查门店关联的仓库是否有发货单
        if($branch_id){
            $row = $deliveryObj->getList('branch_id',array('branch_id' => $branch_id));
            if($row){
                $error_msg = $store_name.'已有发货数据，不能删除';
                $this->end(false,$error_msg);
            }
        }

        $shopObj = app::get('o2o')->model('shop');
        $branchObj = app::get('o2o')->model('branch');

        $shopObj->delete(array('shop_id'=>$shop_id));
        $branchObj->delete(array('branch_id'=>$branch_id));
        $storeObj->delete(array('store_id'=>$store_id));

        //处理组织结构中的数据内容，删除店铺节点，更新父级节点的子节点标记
        $orgObj->delete(array('org_id'=>$org_id));

        //处理原来选中的父节点
        if($org_info['parent_id'] > 0){
            $p_org_info = $orgObj->dump(array("org_id"=>$org_info['parent_id']),"haschild");
            $child_arr = $orgObj->getList("org_id",array("parent_id"=>$org_info['parent_id'],'org_type'=>2), 0, -1);
            if(count($child_arr) > 0){
                $org_save_parent_data['haschild'] = $p_org_info['haschild'] | 2;
            }else{
                $org_save_parent_data['haschild'] = $p_org_info['haschild'] ^ 2;
            }
            $orgObj->update($org_save_parent_data,array('org_id'=>$org_info['parent_id']));
        }

        $this->end(true,'删除门店成功！');
    }

}